<script setup lang="ts" name="ResidentArchives">
import {ref, reactive, PropType, watch} from 'vue'
import {FormRules, ElMessage} from 'element-plus'
import {FromItem} from '@/components/dFrom/dFrom'
import {DialogType, SeleteData, ColorTheme} from '@/api/config'
import dDialog from '@/components/dDialog/dDialog.vue'
import dFrom from '@/components/dFrom/dFrom.vue'
import dIcon from '@/components/dIcon.vue'
import {Number, NoNumber, PhoneNumber, NotLeadingAndTrailingSpaces, getIdCardInfor} from '@/util/common'
import {ResidentList, saveResidenArchives} from '@/api/publicHealthExamination/residentArchives'
import {SelectTeamLsit} from '@/api/publicHealthExamination/communitySettings'
import {savePersonToArchives} from '@/api/publicHealthExamination/physicalExaminationRegister'
//是否显示
const props = defineProps({
  //显示
  showDialog: {
    type: Boolean,
    required: true
  },
  //弹窗类型
  dialogType: {
    type: String as PropType<DialogType>,
    required: true
  },
  //数据
  archivesData: {
    type: Object as PropType<Partial<ResidentList>>,
    required: true
  },
  // 民族下拉字典
  seleteNationData: {
    type: Array as PropType<Array<SeleteData>>,
    required: true,
    defult: () => []
  },
  // 社区下拉
  selectTeamLsit: {
    type: Array as PropType<Array<SelectTeamLsit>>,
    required: true,
    defult: () => []
  },
  // 既往史下拉
  pastHistoryLsit: {
    type: Array as PropType<Array<SeleteData>>,
    required: true,
    defult: () => []
  },
  // 身份证读取实例
  idReader: {
    type: Object,
    required: true,
    defult: () => null
  },
  // 是否是其他页面调用的弹窗，用于保存同步档案管理数据的接口。
  otherPageDialog: {
    type: Boolean,
    defualt: false
  }
})

const emits = defineEmits(['close'])

// 弹窗标题定义
const title = ref(props.dialogType === 'add' ? '新增档案' : '编辑档案')

//信息
const formData: Partial<ResidentList> = reactive(props.archivesData)

// 性别下拉
const selectGenderData = ref<Array<SeleteData>>([
  {label: '男', value: '男'},
  {label: '女', value: '女'}
])

// 显示加载状态
const showSaveLoading = ref(false)

//判断身份证
const validatorIdCard = (rule, value, callback) => {
  if (formData.idNo) {
    const infor = getIdCardInfor(formData.idNo)
    if (infor.age === null && infor.sex === null) {
      callback(new Error('请输入正确的身份证号'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

// 表单规则
const rules = reactive<FormRules>({
  idNo: [
    {required: true, message: '请输入身份证号', trigger: ['change', 'blur']},
    {
      message: '请输入正确的身份证号',
      validator: validatorIdCard,
      trigger: ['change', 'blur']
    },
    {
      message: '长度应不超过18个字符',
      max: 18,
      trigger: ['change', 'blur']
    }
  ],
  name: [
    {required: true, message: '请输入姓名', trigger: ['change', 'blur']},
    {
      message: '长度应不超过20个字符',
      max: 20,
      trigger: ['change', 'blur']
    },
    {
      message: '请输入汉字、字母、字符',
      pattern: NoNumber,
      trigger: ['change', 'blur']
    },
    {
      message: '首尾不能为空格',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    }
  ],
  gender: [{required: true, message: '请选择性别', trigger: ['change', 'blur']}],
  phone: [
    {required: true, message: '请输入联系电话', trigger: ['change', 'blur']},
    {
      message: '长度应不超过11个字符',
      max: 11,
      trigger: ['change', 'blur']
    },
    {
      message: '请输入正确的联系电话',
      pattern: PhoneNumber,
      trigger: ['change', 'blur']
    }
  ],
  nation: [{required: true, message: '请选择民族', trigger: ['change', 'blur']}],
  teamId: [{required: true, message: '请选择社区', trigger: ['change', 'blur']}],
  age: [
    {required: true, message: '请输入年龄', trigger: ['change', 'blur']},
    {message: '请输入数字', pattern: Number, trigger: ['change', 'blur']}
  ],
  address: [
    {required: true, message: '请输入居住地址', trigger: ['change', 'blur']},
    {
      message: '请输入汉字、字母、数字、字符，首尾不能为空',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    },
    {
      message: '长度应不超过100个字符',
      max: 100,
      trigger: ['change', 'blur']
    }
  ]
})

//表单项
const fromItems = ref<Array<FromItem>>([
  {
    label: '身份证号',
    placeholder: '请输入身份证号',
    prop: 'idNo',
    type: 'slot',
    slotName: 'idNo'
  },
  {
    label: '姓名',
    placeholder: '请输入姓名',
    prop: 'name',
    type: 'input'
  },
  {
    label: '性别',
    placeholder: '请选择性别',
    prop: 'gender',
    type: 'selete',
    disabled: true,
    seleteData: selectGenderData.value
  },
  {
    label: '年龄',
    placeholder: '请输入年龄',
    prop: 'age',
    type: 'slot',
    slotName: 'age',
    disabled: true
  },
  {
    label: '民族',
    placeholder: '请选择民族',
    prop: 'nation',
    type: 'selete',
    filterable: true,
    seleteData: props.seleteNationData
  },
  {
    label: '联系电话',
    placeholder: '请输入联系电话',
    prop: 'phone',
    type: 'input'
  },
  {
    label: '社区',
    placeholder: '请选择社区',
    prop: 'teamId',
    type: 'selete',
    filterable: true,
    seleteData: props.selectTeamLsit
  },
  {
    label: '既往史',
    placeholder: '请选既往史',
    prop: 'pastHistory',
    type: 'selete',
    filterable: true,
    seleteData: props.pastHistoryLsit
  },
  {
    label: '居住地址',
    placeholder: '请输入居住地址',
    prop: 'address',
    type: 'input',
    style: {'grid-column': '1/3'}
  }
])

//表单清除控制
const resetFieldsFlag = ref(false)

const validateFlag = ref(false)

// 确认按钮
const onConfirm = () => {
  validateFlag.value = !validateFlag.value
}

/**
 * @description: 身份证读卡器读取身份信息
 * @return {*}
 */
const onReadIdCard = () => {
  props.idReader &&
    props.idReader
      .readIdCard()
      .then((res) => {
        let nation
        // 遍历民族字典，拿到字典值
        props.seleteNationData.forEach((item) => {
          item.label === res.nation + '族' && (nation = item.value)
        })
        formData.idNo = res.idNum // 身份证号
        formData.name = res.name // 姓名
        formData.nation = nation // 民族
        formData.address = res.address // 地址
        formData.portrait = res.photo // 头像
      })
      .catch((err) => {
        console.warn(err)
      })
}

//关闭
const onClose = () => {
  emits('close')
  //关闭后清除表单数据以及表单验证数据 可根据具体业务自行调整
  resetFieldsFlag.value = !resetFieldsFlag.value
}

//取消按钮
const onCancel = () => {
  onClose()
}

//表单验证通过事件
const onSubmit = () => {
  showSaveLoading.value = true
  const params = {
    id: formData.id,
    idNo: formData.idNo || '',
    name: formData.name || '',
    gender: formData.gender || '',
    nation: formData.nation || '',
    age: formData.age || '',
    address: formData.address || '',
    teamId: formData.teamId || '',
    portrait: formData.portrait || '',
    phone: formData.phone || '',
    pastHistory: formData.pastHistory || null
  }
  // 如果是非档案管理的页面，需要调取另一个接口，同步档案和页面数据。
  props.otherPageDialog
    ? savePersonToArchives(params)
      .then(() => {
        showSaveLoading.value = false
        ElMessage.success('修改成功!')
        emits('close')
      })
      .catch((error) => {
        showSaveLoading.value = false
        console.warn(error)
      })
    : saveResidenArchives(params)
      .then(() => {
        showSaveLoading.value = false
        ElMessage.success('保存成功！')
        emits('close')
      })
      .catch((error) => {
        showSaveLoading.value = false
        console.warn(error)
      })
}

// 身份证号改变后性别和年龄一起变
watch(
  () => formData.idNo,
  () => {
    if (formData.idNo) {
      const infor = getIdCardInfor(formData.idNo)
      formData.age = infor.age || ''
      formData.gender = infor.sex === 1 ? '男' : infor.sex === 2 ? '女' : ''
    } else {
      formData.age = ''
      formData.gender = ''
    }
  }
)

// 改变社区，居住地址跟着改变
watch(
  () => formData.teamId,
  () => {
    if (formData.teamId) {
      const index = props.selectTeamLsit.findIndex((item) => {
        return item.value === formData.teamId
      })
      formData.address = props.selectTeamLsit[index]?.address
    } else {
      formData.address = ''
    }
  }
)
</script>

<template>
  <d-dialog
    :title="title"
    :show-dialog="showDialog"
    :width="800"
    :show-save-loading="showSaveLoading"
    @cancel="onCancel"
    @confirm="onConfirm"
    @close="onClose"
  >
    <div class="resident-archives">
      <el-avatar :src="formData.portrait" shape="square" @error="() => true">
        <img src="@/assets/image/default-avatar.png">
      </el-avatar>
      <d-from
        label-position="right"
        :label-width="100"
        :reset-fields-flag="resetFieldsFlag"
        :validate-flag="validateFlag"
        :rules="rules"
        :form-data="formData"
        :form-items="fromItems"
        :form-line-num="2"
        @submit="onSubmit"
      >
        <template #idNo>
          <el-input v-model="formData.idNo" placeholder="请输入身份证号" :disabled="props.dialogType === 'edit'">
            <template v-if="props.dialogType === 'add'" #suffix>
              <d-icon
                :icon-config="{
                  icon: 'common-id-card',
                  type: 'custom',
                  size: 20,
                  color: ColorTheme
                }"
                @click="onReadIdCard"
              />
            </template>
          </el-input>
        </template>
        <template #age>
          <el-input v-model="formData.age" placeholder="请输入年龄" clearable disabled controls-position="right">
            <template #append>
              岁
            </template>
          </el-input>
        </template>
      </d-from>
    </div>
  </d-dialog>
</template>
<style scoped lang="less">
.resident-archives {
  display: flex;
  padding: 0 20px;
  form {
    width: 100%;
  }
  .el-avatar {
    width: 120px;
    height: 150px;
  }
  :deep(.el-input-group__append) {
    background: #dcdee2 !important;
  }
}
</style>
